package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.Company;
import com.amazon.shop.entity.Language;
import com.amazon.shop.entity.auth.Apartments;
import com.amazon.shop.entity.auth.Roles;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.CompanyVo;
import com.amazon.shop.vo.LanguageVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-29
 */
@RestController
@RequestMapping("/shop/company")
@Api(tags = "公司模块")
public class CompanyController {
    @Resource
    private CompanyService companyService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private LanguageService languageService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private ApartmentsService apartmentsService;

    /**
     * 更新公司信息
     *
     * @param companyVo
     * @param token
     * @return
     */
    @SystemLog(value = "新增公司信息")
    @PostMapping("/saveCompany")
    @ApiOperation(value = "新增公司信息")
    @Transactional
    public CommonResult saveCompany(@RequestBody CompanyVo companyVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "4");
        if (flag) {
            //属性对拷
            Company company = new Company();
            BeanUtils.copyProperties(companyVo, company);

            //自定义公司编号
            String companyId = UUID.randomUUID().toString().replace("-", "");
            company.setCompanyId(companyId);

            //更新语言
            List<LanguageVo> languageVos = companyVo.getLanguageVos();
            List<Language> languageList = languageVos.stream().map((vo) -> {
                String languageName = vo.getLanguage();

                //设置语言属性
                Language language = new Language();
                language.setCompanyId(companyId);
                language.setLanguage(languageName);

                return language;
            }).collect(Collectors.toList());
            //批量更新语言信息
            languageService.saveOrUpdateBatch(languageList);

            //更新公司信息
            companyService.saveOrUpdate(company);

            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success("更新公司信息成功")
                    .put("list", companyId)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 查看公司信息
     *
     * @param token
     * @return
     */
    @GetMapping("/getCompanyList")
    @ApiOperation(value = "查看公司信息")
    public CommonResult getCompanyList(String token) {
        boolean flag = permissionsService.getPermissionList(token, "3");
        if (flag) {
            Company company = getCompany(token);
            //属性对拷
            CompanyVo companyVo = new CompanyVo();
            BeanUtils.copyProperties(company, companyVo);

            //根据公司编号查询公司语言信息
            String companyId = company.getCompanyId();
            QueryWrapper<Language> languageQueryWrapper = new QueryWrapper<>();
            languageQueryWrapper.eq("company_id", companyId);
            List<Language> languageList = languageService.list(languageQueryWrapper);
            List<LanguageVo> languageVos = languageList.stream().map((language) -> {
                LanguageVo languageVo = new LanguageVo();
                //属性对拷
                BeanUtils.copyProperties(language, languageVo);
                return languageVo;
            }).collect(Collectors.toList());
            //设置语言信息
            companyVo.setLanguageVos(languageVos);
            return CommonResult.success("公司信息查询成功").put("companyVo", companyVo);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 更新公司信息
     *
     * @param companyVo
     * @param token
     * @return
     */
    @SystemLog(value = "更新公司信息")
    @PostMapping("/updateCompany")
    @ApiOperation(value = "更新公司信息")
    @Transactional
    public CommonResult updateCompany(@RequestBody CompanyVo companyVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "4");
        if (flag) {
            //根据token查询公司信息
            Company company = getCompany(token);

            //根据公司编号修改公司信息
            BeanUtils.copyProperties(companyVo, company);

            //更新公司信息
            companyService.updateById(company);

            //根据公司编号查询语言信息
            String companyId = company.getCompanyId();
            QueryWrapper<Language> languageQueryWrapper = new QueryWrapper<>();
            languageQueryWrapper.eq("company_id", companyId);
            List<Language> languages = languageService.list(languageQueryWrapper);

            //删除公司语言信息
            languageService.removeByIds(languages);

            //保存语言信息
            List<LanguageVo> languageVos = companyVo.getLanguageVos();
            List<Language> languageList = languageVos.stream().map((vo) -> {
                Language language = new Language();
                //属性对拷
                BeanUtils.copyProperties(vo, language);
                //设置公司编号
                language.setCompanyId(companyId);
                return language;
            }).collect(Collectors.toList());

            //批量保存语言信息
            languageService.saveBatch(languageList);

            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success("更新公司成功")
                    .put("list", companyId)
                    .put("salesman", userRealName);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取公司信息
     *
     * @param token
     * @return
     */
    private Company getCompany(String token) {
        //根据token查询用户信息
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("token", token);
        Users users = usersService.getOne(usersQueryWrapper);

        //根据用户编号查询角色信息
        String userId = users.getUserId();
        QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
        usersRolesQueryWrapper.eq("user_id", userId);
        UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);

        //根据角色编号查询角色信息
        String roleId = usersRoles.getRoleId();
        Roles roles = rolesService.getById(roleId);

        //根据部门名称查询部门信息
        String apartmentName = roles.getApartmentName();
        QueryWrapper<Apartments> apartmentsQueryWrapper = new QueryWrapper<>();
        apartmentsQueryWrapper.eq("apartment_name", apartmentName);
        Apartments apartments = apartmentsService.getOne(apartmentsQueryWrapper);

        //根据公司名称查询公司信息
        String companyName = apartments.getCompany();
        QueryWrapper<Company> companyQueryWrapper = new QueryWrapper<>();
        companyQueryWrapper.eq("company_name", companyName);
        Company company = companyService.getOne(companyQueryWrapper);
        return company;
    }
}

